﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;


namespace Tool_operation
{
    public partial class HOME : Form
    {
        public HOME()
        {
            InitializeComponent();
            Tab1.SelectedTab = login;
            this.comboBox1.AutoCompleteMode = System.Windows.Forms.AutoCompleteMode.Suggest;
            this.comboBox1.AutoCompleteSource = System.Windows.Forms.AutoCompleteSource.CustomSource;
            Tab1.SizeMode = TabSizeMode.Fixed;
            Tab1.ItemSize = new Size(0, 1);
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            // 禁止用户改变DataGridView1的所有列的列宽  
            dataGridView1.AllowUserToResizeColumns = false;  
            //禁止用户改变DataGridView1の所有行的行高  
            dataGridView1.AllowUserToResizeRows = false;

            // 禁止用户改变列头的高度  
            dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
            dataGridView1.ReadOnly = true;
            //Column3.ReadOnly = true;//DataGridViewCheckBoxColumn


        }
        /// <summary>
        /// 上工具数据
        /// </summary>
        Users upper =new Users();
        /// <summary>
        /// 下工具数据
        /// </summary>
        Users lower = new Users();
        /// <summary>
        /// 增加页面工具数据
        /// </summary>
        Users Plus_Type = new Users();
        /// <summary>
        /// 语言包数据
        /// </summary>
        JObject Data_Json;
        /// <summary>
        /// 当前使用数据id
        /// </summary>
        int record;
        /// <summary>
        /// 当前使用工具数据
        /// </summary>
        Users Now = new Users();
        /// <summary>
        /// 中文语言包数据
        /// </summary>
        List<string> zh_ch_name = new List<string>();

        /// <summary>
        /// 窗口初始化
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void HOME_Load(object sender, EventArgs e)
        {
            //Current_directory = System.Environment.CurrentDirectory +"\\";
            Init(1);
            button10.BackColor = Color.Red;
            button10.Enabled = false;
            button11.BackColor = Color.LightGreen;
            button11.Enabled = false;
        }
        /// <summary>
        /// 减页面初始化
        /// </summary>
        /// <param name="parameter"></param>
        /// <param name="route"></param>
        /// <returns></returns>
        public int Init(int parameter,string route = @"plugins\")
        {
            Data_Json = JObject.Parse(System.IO.File.ReadAllText(@"Configuration\ch-CN.language"));
            if(GetAllFileNames(route, parameter) == 1)
            {
                Currently_used(parameter);
                dataGridView1.Rows.Clear();
                Add_Data();
                if(dataGridView1.Rows.Count == 0)
                {
                    MessageBox.Show("未发现工具dll");
                }
                return 1;
            }
            return -1;

        }
        /// <summary>
        /// 设置当前使用数据
        /// </summary>
        /// <param name="Current_data"></param>
        public void Currently_used(int Current_data)
        {
            if (Current_data == 1) { Now = upper; record = 1; }
            else if(Current_data == 2) { Now = lower; record = 2; }
            else if (Current_data == 3) { Now = Plus_Type; record = 3; }

        }
        /// <summary>
        /// 表格增加工具数据
        /// </summary>
        public void Add_Data()
        {
            string en_US;
            string zh_CH;
            if (Now.Current_Data.Count > 0)
            {
                foreach (var i in Now.Current_Data)
                {
                    string F = "";
                    if (i.IndexOf("Tool.dll") != -1)
                    {
                        F = i.Substring(0, i.Length - 4);
                    }
                    else if (i.IndexOf("Tool2.dll") != -1)
                    {
                        F = i.Substring(0, i.Length - 4);
                    }
                    //else
                    //{
                    //    F = i.Substring(0, i.Length - 4);
                    //}
                    if (F != "")
                    {
                        en_US = F.ToString();
                        try
                        {
                            zh_CH = Data_Json[F].ToString();
                            zh_ch_name.Add(zh_CH);
                            // MessageBox.Show(en_US+"++"+ zh_CH);
                            //string PATHS = @"" + Now.Current_Path + "\\" + en_US + ".dll";
                            //System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(PATHS);
                            //FileInfo fi = new FileInfo(PATHS);
                            //dataGridView1.Rows.Add(zh_CH, en_US, fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"), info.FileVersion, 0);
                        }
                        catch
                        {
                            zh_CH = "语言未匹配到";

                        }
                        string PATHS = @"" + Now.Current_Path + "\\" + en_US + ".dll";
                        System.Diagnostics.FileVersionInfo info = System.Diagnostics.FileVersionInfo.GetVersionInfo(PATHS);
                        FileInfo fi = new FileInfo(PATHS);
                        dataGridView1.Rows.Add(zh_CH, en_US, fi.LastWriteTime.ToString("yyyy-MM-dd HH:mm:ss"), info.FileVersion, 0);
                        label4.Text = "当前工具数量：" + dataGridView1.Rows.Count;
                    }
                    
                }
            }
        }
        /// <summary>
        /// 切换工具显示
        /// </summary>
        /// <param name="type"></param>
        public void Switch(int type)
        {
            dataGridView1.Rows.Clear();
            Currently_used(type);
            Add_Data();
        }
        /// <summary>
        /// 获取目录文件合集
        /// </summary>
        /// <param name="path">目录</param>
        /// <param name="cha">类型</param>
        /// <returns></returns>
        public int GetAllFileNames(string path, int cha)
        {
            List<FileInfo> folder = new DirectoryInfo(path).GetFiles("*.dll").ToList();
            if(folder.Count == 0)
            {
                MessageBox.Show("没有找到工具dll文件");
                return -1;
            }
            if (cha == 1)
            {
                upper.Current_Data = folder.Select(x => x.Name).ToList();
                upper.Current_Path = folder.Select(x => x.DirectoryName).ToList()[0] + "\\";
                return 1;
            }
            else if (cha == 2)
            {
                lower.Current_Data = folder.Select(x => x.Name).ToList();
                lower.Current_Path = folder.Select(x => x.DirectoryName).ToList()[0] + "\\";
                return 1;
            }
            else
            {
                Plus_Type.Current_Data = folder.Select(x => x.Name).ToList();
                Plus_Type.Current_Path = folder.Select(x => x.DirectoryName).ToList()[0] + "\\";
                return 1;
            }
        }
        /// <summary>
        /// 点击表头事件（预留）
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView1_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            //if(dataGridView1.Columns[e.ColumnIndex].Name == "Column5")
            //{
            //    int k = dataGridView1.SelectedRows.Count;
            //    if (k != dataGridView1.Rows.Count-2)//因为还有一行为统计行所以减2
            //    {

            //        for (int i = k; i >= 1; i--)
            //        {
            //            dataGridView1.Rows[dataGridView1.SelectedRows[i-1].Index].Cells[4].Value = true;

            //        }
            //    }
            //}
        }
        /// <summary>
        /// 模糊搜索按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                for (int i = 0; i < this.dataGridView1.Rows.Count; i++)//遍历所有选中的行
                {
                    if (dataGridView1.Rows[i].Cells[0].Value.ToString() == comboBox1.Text)
                    {
                        dataGridView1.CurrentCell = this.dataGridView1.Rows[i].Cells[0];
                        return;
                    }
                }
                MessageBox.Show("未找到此工具");
            }
            catch
            {

            }
        }
        /// <summary>
        /// 选中按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button2_Click(object sender, EventArgs e)
        {
            int k = dataGridView1.SelectedRows.Count;
            if (k != dataGridView1.Rows.Count - 2)//因为还有一行为统计行所以减2
            {

                for (int i = k; i >= 1; i--)//从下往上删，避免沙漏效应
                {
                    dataGridView1.Rows[dataGridView1.SelectedRows[i - 1].Index].Cells[4].Value = 1;

                }
            }
        }
        /// <summary>
        /// 取消选中按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button3_Click(object sender, EventArgs e)
        {
            int k = dataGridView1.SelectedRows.Count;
            if (k != dataGridView1.Rows.Count - 2)//因为还有一行为统计行所以减2
            {

                for (int i = k; i >= 1; i--)//从下往上删，避免沙漏效应
                {
                    dataGridView1.Rows[dataGridView1.SelectedRows[i - 1].Index].Cells[4].Value = 0;

                }
            }
        }
        /// <summary>
        /// 删除按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button4_Click(object sender, EventArgs e)
        {
            DialogResult dr = MessageBox.Show("确定删除当前文件？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.Cancel)
            {
                return;
            }
            List<int> Del = new List<int>();
            for (int i = 0; i < dataGridView1.Rows.Count; i++)//从下往上删，避免沙漏效应
            {
                if (dataGridView1.Rows[i].Cells[4].Value.ToString() == "1")
                {
                    Del.Add(i);
                }
            }
            string Sc = "";
            if(Del.Count != 0)
            {
                foreach (var i in Del)
                {
                    try
                    {
                        File.Delete(Now.Current_Path + dataGridView1.Rows[i].Cells[1].Value.ToString() + ".dll");
                        Sc = Sc + dataGridView1.Rows[i].Cells[1].Value.ToString() + "\n";
                    }
                    catch
                    {
                        MessageBox.Show("无法删除该文件:" + dataGridView1.Rows[i].Cells[1].Value.ToString());
                        return;
                    }
                }
                MessageBox.Show("删除:" + dataGridView1.Rows[Del[0]].Cells[0].Value.ToString() + "等" + Del.Count + "个工具,成功!");
                dataGridView2.Rows.Add(DateTime.Now.ToString(), "删除", "删除:\n" + Sc + "等工具,成功!");
                //Init(1);
                Del.Clear();
                GetAllFileNames(Now.Current_Path, record);
                Switch(record);
            }
            else
            {
                MessageBox.Show("没有选中数据");
            }
            
        }

        /// <summary>
        /// 切换到增加页面按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button5_Click(object sender, EventArgs e)
        {
            Tab1.SelectedTab = plus;
            Get_Path();
        }
        /// <summary>
        /// 增加页面切换目录按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button6_Click(object sender, EventArgs e)
        {
            Get_Path();
        }
        /// <summary>
        /// 对话框选择获取目录并显示到增加页面文本框
        /// </summary>
        public void Get_Path()
        {
            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "选择工具所在目录，例如（plugins）";  //提示的文字
            if (folder.ShowDialog() == DialogResult.OK)
            {

                textBox2.Text = folder.SelectedPath;
                GetAllFileNames(folder.SelectedPath, 3);
            }
            else
            {
                MessageBox.Show("你已取消操作");
                Tab1.SelectedTab = reduce;
                return;
            }
            plus_init();
        }
        /// <summary>
        /// 初始化增加页面工具数据
        /// </summary>
        public void plus_init()
        {
            GetAllFileNames(@"" + textBox2.Text,2);
        }
        /// <summary>
        /// 增加页面替换已有按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button7_Click(object sender, EventArgs e)
        {
            Copy_Replace();
            MessageBox.Show("替换操作成功");
        }
        /// <summary>
        /// 增加页面切换到减页面按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button9_Click(object sender, EventArgs e)
        {

            Tab1.SelectedTab = reduce;
            Init(1);

        }
        /// <summary>
        /// 文件复制
        /// </summary>
        /// <param name="filePathName">待复制文件</param>
        /// <param name="toFilesPath">目的地文件夹</param>
        public void SaveFile(string filePathName, string toFilesPath)
        {
            FileInfo file = new FileInfo(filePathName);
            string newFileName = file.Name;
            file.CopyTo(toFilesPath + @"\" + newFileName, true);
        }
        /// <summary>
        /// 替换已有操作
        /// </summary>
        public void Copy_Replace()
        {
            string Th = "";
            for (int i = 0; i < Now.Current_Data.Count; i++)
            {
                foreach (var j in Plus_Type.Current_Data)
                {
                    if (Now.Current_Data[i] == j)
                    {
                        SaveFile(textBox2.Text + "\\" + j, upper.Current_Path);
                        Th = Th + j + "\n";
                        break;
                    }
                }
            }
            dataGridView2.Rows.Add(DateTime.Now.ToString(), "替换", "替换已有:\n" + Th + "替换到目录" + upper.Current_Path +"下,成功!");
        }
        /// <summary>
        /// 已有增加操作
        /// </summary>
        public void Increase()
        { 
            List<string> Now_data = Plus_Type.Current_Data;
            foreach(var P in upper.Current_Data)
            {
                foreach (var j in Now_data)
                {
                    if (P == j)
                    {
                        Now_data.Remove(j);
                        break;
                    }
                }
            }
            string Zj = "";
            foreach (var k in Now_data)
            {
                SaveFile(textBox2.Text + "\\" + k, upper.Current_Path);
                Zj = Zj + k + "\n";
            }
            dataGridView2.Rows.Add(DateTime.Now.ToString(), "增加", "已有增加:\n" + Zj + "到目录" + upper.Current_Path +"下,成功!");
        }
        /// <summary>
        /// 增加页面已有增加按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button8_Click(object sender, EventArgs e)
        {
            Increase();
            MessageBox.Show("操作完成");
        }
        /// <summary>
        /// 搜索框输入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void comboBox1_TextUpdate(object sender, EventArgs e)
        {
            ComboBox cbBox = (ComboBox)sender;
            List<string> listNew = new List<string>();
            cbBox.Items.Clear();
            foreach (var item in zh_ch_name)  //已有数据
            {
                if (item.Contains(cbBox.Text))
                {
                    listNew.Add(item);
                }
            }
            cbBox.Items.AddRange(listNew.ToArray());
            cbBox.SelectionStart = cbBox.Text.Length;
            Cursor = Cursors.Default;
            cbBox.DroppedDown = true;
        }

        /// <summary>
        /// 密码框输入事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            if (textBox1.Text == "1")
            {
                Tab1.SelectedTab = reduce;
                return;
            }
            if(textBox1.Text == "kws88888888")
            {
                Tab1.SelectedTab = reduce;
                return;
            }

            if (textBox1.Text == "KWS88888888")
            {
                Tab1.SelectedTab = reduce;
                return;
            }

        }
        /// <summary>
        /// 减页面换工具目录按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button12_Click_1(object sender, EventArgs e)
        {

            FolderBrowserDialog folder = new FolderBrowserDialog();
            folder.Description = "选择工具所在目录，例如（plugins）";  //提示的文字
            if (folder.ShowDialog() == DialogResult.OK)
            {
                //lower.Current_Data.Clear();
                //lower.Current_Path = "";
                if (Init(2, folder.SelectedPath) == 1)
                {
                    button10.Enabled = false;
                    button10.BackColor = Color.LightGreen;
                    button11.Enabled = true;
                    button11.BackColor = Color.Gray;
                }
                dataGridView2.Rows.Add(DateTime.Now.ToString(), "打开目录", "打开目录:\n" + folder.SelectedPath + "成功!");
            }
        }
        /// <summary>
        /// 右键复制文件名事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 复制文件名ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count == 1)
            {

                Clipboard.SetDataObject(dataGridView1.Rows[dataGridView1.SelectedRows[0].Index].Cells[1].Value);
                MessageBox.Show("复制文件名成功");
                dataGridView2.Rows.Add(DateTime.Now.ToString(), "复制文件名", "复制:" + dataGridView1.Rows[dataGridView1.SelectedRows[0].Index].Cells[1].Value + "成功!");
            }
            else
            {
                MessageBox.Show("你要复制的名字太多了，我不干了");
            }
        }
        /// <summary>
        /// 右键复制文件事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 复制文件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int cop = dataGridView1.SelectedRows.Count;
            string Fz = "";
            if (cop != dataGridView1.Rows.Count - 2)//因为还有一行为统计行所以减2
            {
                System.Collections.Specialized.StringCollection strcoll = new System.Collections.Specialized.StringCollection();
                for (int i = 0; i <= cop - 1; i++)//从下往上删，避免沙漏效应
                {
                    strcoll.Add(@"" + Now.Current_Path + dataGridView1.Rows[dataGridView1.SelectedRows[i].Index].Cells[1].Value + ".dll");
                    Fz = Fz + dataGridView1.Rows[dataGridView1.SelectedRows[i].Index].Cells[1].Value + "\n";

                }
                dataGridView2.Rows.Add(DateTime.Now.ToString(), "复制文件", "复制文件:\n" + Fz + "工具,成功!");
                Clipboard.SetFileDropList(strcoll);
                MessageBox.Show("复制文件成功");
                
            }
        }
        /// <summary>
        /// 右键粘贴事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 粘贴ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var file = Clipboard.GetFileDropList();
            DialogResult dr = MessageBox.Show("确定粘贴" + file.Count +"个文件？", "提示", MessageBoxButtons.OKCancel, MessageBoxIcon.Question);
            if (dr == DialogResult.OK)
            {
                try
                {
                    string Zt = "";
                    foreach (var F in file)
                    {

                        SaveFile(F, Now.Current_Path);
                        Zt = Zt + F + "\n";
                        //System.IO.File.Copy(F, Now.Current_Path);
                    }
                    dataGridView2.Rows.Add(DateTime.Now.ToString(), "粘贴文件", "粘贴文件:\n" + Zt + "等工具到 " + Now.Current_Path + ",成功!");
                    GetAllFileNames(Now.Current_Path, record);
                    Switch(record);
                    MessageBox.Show("粘贴成功");
                }
                catch
                {
                    MessageBox.Show("粘贴异常");
                }
                
            }
        }
        /// <summary>
        /// 减页面切换到下目录按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button10_Click(object sender, EventArgs e)
        {
            Switch(2);
            button10.Enabled = false;
            button10.BackColor = Color.LightGreen;
            button11.Enabled = true;
            button11.BackColor = Color.Gray;
        }
        /// <summary>
        /// 减页面切换上按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button11_Click(object sender, EventArgs e)
        {
            Switch(1);
            button11.Enabled = false;
            button11.BackColor = Color.LightGreen;
            button10.Enabled = true;
            button10.BackColor = Color.Gray;
        }
        /// <summary>
        /// 减页面打开当前目录按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button15_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start(Now.Current_Path);
        }
        /// <summary>
        /// 减页面日志按钮点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button16_Click(object sender, EventArgs e)
        {
            Tab1.SelectedTab = log;
        }
        /// <summary>
        /// 日志页面右键返回事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 返回ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Tab1.SelectedTab = reduce;
        }
        /// <summary>
        /// 日志页面右键清空事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void 清空ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            dataGridView2.Rows.Clear();
            richTextBox1.Text = "";
        }
        /// <summary>
        /// 日志页面表格单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            richTextBox1.Text = dataGridView2.Rows[dataGridView2.SelectedRows[0].Index].Cells[2].Value.ToString();
        }
    }
    /// <summary>
    /// 工具数据类
    /// </summary>
    public class Users
    {
        /// <summary>
        /// 工具来源目录
        /// </summary>
        public string Current_Path;
        /// <summary>
        /// 工具合集目录
        /// </summary>
        public List<string> Current_Data;

    }

}
